package GoodsActivityService

import (
	"gdshop-back-end-go/admin-api/app/request/GoodsActivityReq"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/request/BaseReq"
	"gdshop-back-end-go/common/response"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

func GetRule(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	activityId := r.GetInt("activity_id", 0)
	if activityId < 1 {
		return response.FailByRequestMessage(nil, "活动ID不能为空")
	}
	activityType := r.GetString("activity_type")
	where := map[string]interface{}{
		"activity_id": activityId,
	}
	if activityType == "tuan" {
		// 团购规则
		var tmp *GoodsActivityReq.SetRuleTuan
		err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "goods_activity_rule").Where(where).Scan(&tmp)
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
		if tmp == nil {
			tmp = &GoodsActivityReq.SetRuleTuan{
				Rules: GoodsActivityReq.RulesTuanItem{
					ExceedPolicy: 1, // 给默认值
				},
			}
		}
		return response.SuccessByRequestMessageData(nil, "成功", tmp)
	}

	if activityType == "seckill" {
		// 秒杀规则
		var tmp *GoodsActivityReq.SetRuleSeckill
		err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "goods_activity_rule").Where(where).Scan(&tmp)
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
		if tmp == nil {
			return response.SuccessByRequestMessageData(nil, "成功", g.Map{})
		}
		return response.SuccessByRequestMessageData(nil, "成功", tmp)
	}

	// activityType == "default" 默认规则
	var tmp *GoodsActivityReq.SetRule
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "goods_activity_rule").Where(where).Scan(&tmp)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	if tmp == nil {
		tmp = &GoodsActivityReq.SetRule{
			Rules: []GoodsActivityReq.RulesItem{},
		}
	}
	return response.SuccessByRequestMessageData(nil, "成功", tmp)
}
